<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace app\supplier\controller;
use think\Session;
use app\supplier\controller\Base;
use app\supplier\model\ProductModel;
use app\supplier\model\PtypeModel;
use app\supplier\model\FieldModel;
use app\supplier\model\CountryModel;
use app\supplier\model\MakeModel;
use app\supplier\model\SeriesModel;
use app\supplier\model\MatorModel;

class Product extends Base
{
	/**
	 * 产品对象
	 * @return mixed
	 */
	public $product_obj;
	
	/**
	 * 产品类型对象
	 * @return mixed
	 */
	public $ptype_obj;
	
	/**
	 * 车型对象
	 * @return mixed
	 */
	public $mator_obj;
	
	/**
	 * 构造函数
	 * @return mixed
	 */
	public function __construct()
	{
		parent::__construct();
		$this->product_obj = new ProductModel(); 
		$this->ptype_obj = new PtypeModel(); 
		$this->mator_obj = new MatorModel();	
	}
	
	/**
	 * 产品列表
	 * @return mixed
	 */
    public function lists()
    {
		$ptype = $this->ptype_obj->getPtypeList(['export'=>1]);
		$psale = config('product_sale_list');
		$input = input('get.');
		if(isset($input['data'])){
			$supplier_id = Session::get('supplier_id');
			$input['supplier_id'] = $supplier_id;
			$data = $this->product_obj->getProductList($input);
			if(!empty($data['list']['data'])){
				$ptype_arr = array();
				foreach($ptype['list'] as $_p){
					$ptype_arr[$_p['id']] = $_p['type_name'];
				}
				foreach($data['list']['data'] as $key=>$val){
					if(is_numeric($val['create_time'])){
						$data['list']['data'][$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
					}
					$data['list']['data'][$key]['type_name'] = $ptype_arr[$val['type_id']];
					$data['list']['data'][$key]['sale_name'] = $psale[$val['product_sale']];
				}
			}
			$result = array('code'=>0,'msg'=>'','count'=>$data['list']['total'],'data'=>$data['list']['data']);
			return json($result);
		}else{
			$this->assign('ptype',$ptype['list']);
			$this->assign('psale',$psale);
			return view('index');
		}
    }
	
	/**
	 * 产品导入页面
	 * @return mixed
	 */
	public function import()
	{
		$input = input('post.');
		if(isset($input['u_type']) && !empty($input['u_type'])){
			$upload_dir = config('upload_dir').$input['dir'].'/';
			$file = request()->file($input['u_type']);
			$info = $file->move($upload_dir);
			$import_data = array();
			switch($input['u_type']){
				case 'productImport':
					$show_file = $info->getSaveName();
					$extension = strtolower( pathinfo($show_file, PATHINFO_EXTENSION) );
					if($extension == 'xlsx') {
						$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}else if($extension == 'xls'){
						$objReader =\PHPExcel_IOFactory::createReader('Excel5');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}
					$excel_array = $objPHPExcel->getsheet(0)->toArray();
					$excel_array = array_splice($excel_array,2);
					foreach($excel_array as $_arr){
						if(empty($_arr[0])){
							continue;
						}
						array_push(
							$import_data,
							array(
								'product_code'=>$_arr[0],
								'product_name'=>$_arr[1],
								'type_code'=>$_arr[2],
								'product_sale'=>$_arr[3],
								'product_dw'=>$_arr[4],
								'product_cg'=>$_arr[5],
								'product_demo'=>$_arr[6]
							)
						);
					}
					$flag = $this->product_obj->productImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'sizeImport':
					$show_file = $info->getSaveName();
					$extension = strtolower( pathinfo($show_file, PATHINFO_EXTENSION) );
					if($extension == 'xlsx') {
						$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}else if($extension == 'xls'){
						$objReader =\PHPExcel_IOFactory::createReader('Excel5');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}
					$excel_array = $objPHPExcel->getsheet(0)->toArray();
					$excel_array = array_splice($excel_array,2);
					$size_arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
					foreach($excel_array as $_key=>$_arr){
						if(empty($_arr[0])){
							continue;
						}
						$data_arr = array();
						for($i=0;$i<=25;$i++){
							if(isset($_arr[$i+1]) && !empty($_arr[$i+1])){
								$data_arr['product_code'] = $_arr[0];
								$data_arr['size_'.$size_arr[$i]] = $_arr[$i+1];
							}
						}
						if(!empty($data_arr)){
							array_push($import_data,$data_arr);
						}
					}
					$flag = $this->product_obj->productSizeImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'paramsImport':
					$show_file = $info->getSaveName();
					$extension = strtolower( pathinfo($show_file, PATHINFO_EXTENSION) );
					if($extension == 'xlsx') {
						$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}else if($extension == 'xls'){
						$objReader =\PHPExcel_IOFactory::createReader('Excel5');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}
					$excel_array = $objPHPExcel->getsheet(0)->toArray();
					$excel_array = array_splice($excel_array,2);
					foreach($excel_array as $_arr){
						if(empty($_arr[0])){
							continue;
						}
						array_push(
							$import_data,
							array(
								'product_code'=>$_arr[0],
								'product_title'=>$_arr[1],
								'product_content'=>$_arr[2]
							)
						);
					}
					$flag = $this->product_obj->productContentImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'changeImport':
					$show_file = $info->getSaveName();
					$extension = strtolower( pathinfo($show_file, PATHINFO_EXTENSION) );
					if($extension == 'xlsx') {
						$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}else if($extension == 'xls'){
						$objReader =\PHPExcel_IOFactory::createReader('Excel5');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}
					$excel_array = $objPHPExcel->getsheet(0)->toArray();
					$excel_array = array_splice($excel_array,2);
					foreach($excel_array as $_arr){
						if(empty($_arr[0])){
							continue;
						}
						array_push(
							$import_data,
							array(
								'product_code'=>$_arr[0],
								'exchange_code'=>$_arr[1],
								'fact_code'=>$_arr[2],
								'fact_name'=>$_arr[3],
								'fact_type'=>$_arr[4],
								'fact_demo'=>$_arr[5],
							)
						);
					}
					$flag = $this->product_obj->productChangeImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'matorImport':
					$show_file = $info->getSaveName();
					$extension = strtolower( pathinfo($show_file, PATHINFO_EXTENSION) );
					if($extension == 'xlsx') {
						$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}else if($extension == 'xls'){
						$objReader =\PHPExcel_IOFactory::createReader('Excel5');
						$objPHPExcel = $objReader->load($upload_dir.$info->getSaveName(), $encode = 'utf-8');
					}
					$excel_array = $objPHPExcel->getsheet(0)->toArray();
					$excel_array = array_splice($excel_array,2);
					foreach($excel_array as $_arr){
						if(empty($_arr[0])){
							continue;
						}
						array_push(
							$import_data,
							array(
								'product_code'=>$_arr[0],
								'mator_code'=>$_arr[1]
							)
						);
					}
					$flag = $this->product_obj->productMatorImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'fileImport':
					$zip = new \ZipArchive; 
					if ($zip->open($upload_dir.$info->getSaveName()) === TRUE){  	
						$zip->extractTo($upload_dir);
						$zip->close();
						$name_info = $info->getInfo();
						$name_arr = pathinfo($name_info['name']);
						$files = scandir($upload_dir.$name_arr['filename']);
						foreach($files as $file){
							if($file !='.' && $file !='..'){
								$product_obj = ProductModel::get(['product_code' => $file]);
								if($product_obj != NULL){
									$type_files = scandir($upload_dir.$name_arr['filename'].'/'.$file);
									foreach($type_files as $type_file){
										$file_type = 0;
										switch($type_file){
											case 'Drawing' :
												$file_type = 1;
												break;
											case 'Installation' :
												$file_type = 2;
												break;
										}
										$goods_files = scandir($upload_dir.$name_arr['filename'].'/'.$file.'/'.$type_file);
										foreach($goods_files as $goods_file){
											if(!empty($goods_file) && $goods_file !='.' && $goods_file !='..' && $file_type > 0){
												array_push(
													$import_data,
													array(
														'product_code'=>$file,
														'file_type'=>$file_type,
														'file_name'=>$goods_file,
														'file_url'=>$input['dir'].'/'.$name_arr['filename'].'/'.$file.'/'.$type_file.'/'.$goods_file
													)
												);
											}
										}
									}
								}
							}
						}
					}
					$flag = $this->product_obj->productFileImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
				case 'imageImport':
					$zip = new \ZipArchive; 
					if ($zip->open($upload_dir.$info->getSaveName()) === TRUE){  	
						$zip->extractTo($upload_dir);
						$zip->close();
						$name_info = $info->getInfo();
						$name_arr = pathinfo($name_info['name']);
						$files = scandir($upload_dir.$name_arr['filename']);
						foreach($files as $file){
							if($file !='.' && $file !='..'){
								$product_obj = ProductModel::get(['product_code' => $file]);
								if($product_obj != NULL){
									$goods_files = scandir($upload_dir.$name_arr['filename'].'/'.$file);
									foreach($goods_files as $goods_file){
										if(!empty($goods_file) && $goods_file !='.' && $goods_file !='..'){
											array_push(
												$import_data,
												array(
													'product_code'=>$file,
													'file_name'=>$goods_file,
													'file_url'=>$input['dir'].'/'.$name_arr['filename'].'/'.$file.'/'.$goods_file
												)
											);
										}
									}
								}
							}
						}
					}
					$flag = $this->product_obj->productImagesImport($import_data);
					if(!$flag){
						$result = [
							'code' => 0,
							'msg'  => '导入失败！',
							'list' => array(),
							'data'=>$import_data
						];
					}
					break;
			}
			$result = [
				'code' => 1,
				'msg'  => '导入成功！',
				'list' => array(),
				'data'=>$import_data
			];
			return json($result);
		}else{
			return view('import');
		}
	}
	
	/**
	 * 车型列表
	 * @return mixed
	 */
	public function mator()
	{
		$fieldData = array();
		$field = FieldModel::all();
		foreach($field as $_f){
			$fieldData[$_f['id']] = $_f;
		}
		$countryData = array();
		$country = CountryModel::all();
		foreach($country as $_c){
			$countryData[$_c['id']] = $_c;
		}
		$makeData = array();
		$make = MakeModel::all();
		foreach($make as $_m){
			$makeData[$_m['id']] = $_m;
		}
		$seriesData = array();
		$series = SeriesModel::all();
		foreach($series as $_s){
			$seriesData[$_s['id']] = $_s;
		}
		$input = input('get.');
		if(isset($input['data'])){
			$input['mator_ids'] = array();
			$mator_rows = $this->mator_obj->getSupplierProductSku(array('product_id'=>$input['product_id']));
			foreach($mator_rows as $_m){
				array_push($input['mator_ids'],$_m['mator_id']);
			}
			$data = $this->mator_obj->getMatorList($input);
			if(!empty($data['list']['data'])){
				foreach($data['list']['data'] as $key=>$val){
					$data['list']['data'][$key]['field_country_code'] = $fieldData[$val['field_id']]['field_code'].'-'.$countryData[$val['country_id']]['country_code'];
					$data['list']['data'][$key]['field_country_name'] = $fieldData[$val['field_id']]['field_name'].'-'.$countryData[$val['country_id']]['country_name'];
					$data['list']['data'][$key]['make_name'] = $makeData[$val['make_id']]['make_name'];
					$data['list']['data'][$key]['series_name'] = $seriesData[$val['series_id']]['series_name'];
					$data['list']['data'][$key]['year_name'] = '';
					if($seriesData[$val['series_id']]['from_time'] > 0){
						$data['list']['data'][$key]['year_name'] = date('Y/m',$seriesData[$val['series_id']]['from_time']).'~'.date('Y/m',$seriesData[$val['series_id']]['to_time']);
					}
					if(is_numeric($val['create_time'])){
						$data['list']['data'][$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
					}
				}
			}
			$result = array('code'=>0,'msg'=>'','count'=>$data['list']['total'],'data'=>$data['list']['data']);
			return json($result);
		}else{
			$this->assign('input',$input);
			return view('small');
		}
	}
	
	/**
	 * 互换码列表
	 * @return mixed
	 */
	public function change()
	{
		$input = input('get.');
		if(isset($input['data'])){
			$data = $this->product_obj->getProductChangeList($input);
			$result = array('code'=>0,'msg'=>'','count'=>$data['list']['total'],'data'=>$data['list']['data']);
			return json($result);
		}else{
			$this->assign('input',$input);
			return view('change');
		}
	}
	
	/**
	 * 新增产品页面
	 * @return mixed
	 */
	public function add()
	{
		$ptype = $this->ptype_obj->getPtypeList(['export'=>1]);
		$psale = config('product_sale_list');
		$this->assign('ptype',$ptype['list']);
		$this->assign('psale',$psale);
		return view('add');
	}
	/**
	 * 编辑产品
	 * @return mixed
	 */
	public function edit()
	{
		$show_file = config('show_file_dir');
		$input = input('get.');
		$product = $this->product_obj->getProductView($input);
		$ptype = $this->ptype_obj->getPtypeList(['export'=>1]);
		$product['base']['type_name'] = '';
		foreach($ptype['list'] as $_p){
			if($_p['id'] == $product['base']['type_id']){
				$product['base']['type_name'] = $_p['type_name'];
			}
		}
		$product['p_files']['tz'] = array('TzId'=>0,'TzName'=>'','TzUrl'=>'','TzAurl'=>'');
		$product['p_files']['az'] = array('AzId'=>0,'AzName'=>'','AzUrl'=>'','AzAurl'=>'');
		if(!empty($product['files'])){
			foreach($product['files'] as $key=>$file){
				if($file['file_type'] == 1){
					$product['p_files']['tz']['TzId'] = $file['id'];
					$product['p_files']['tz']['TzName'] = $file['file_name'];
					$product['p_files']['tz']['TzUrl'] = $file['file_url'];
					$product['p_files']['tz']['TzAurl'] = $show_file.$file['file_url'];
					unset($product['files'][$key]);
				}elseif($file['file_type'] == 2){
					$product['p_files']['az']['AzId'] = $file['id'];
					$product['p_files']['az']['AzName'] = $file['file_name'];
					$product['p_files']['az']['AzUrl'] = $file['file_url'];
					$product['p_files']['az']['AzAurl'] = $show_file.$file['file_url'];
					unset($product['files'][$key]);
				}else{
					$product['files'][$key]['file_all_url'] = $show_file.$file['file_url'];
				}
			}
		}
		$files_count = count($product['files']);
		if($files_count < 6){
			$num = 6 - $files_count;
			for($i=0;$i<$num;$i++){
				array_push(
						$product['files'],
						array(
							'id'=>0,
							'product_id'=>$input['id'],
							'file_name'=>'',
							'file_url'=>'',
							'file_type'=>0,
							'file_status'=>0,
							'file_all_url'=>'',
							'file_sort'=>0,
							'create_time'=>0,
							'update_time'=>0
						)	
					);
			}
		}
		$where = array();
		$where['type_id'] = $product['base']['type_id'];
		$size = $this->ptype_obj->getSizeByType($where);
		$size_config = config('size_list');
		$size_list = array();
		foreach($size_config as $_k=>$_s){
			if($size['size_'.strtolower($_s['code'])] == 1){
				array_push(
					$size_list,
					array(
						'code'=>$_s['code'],
						'name'=>$_s['name'],
						'input'=>'size_'.strtolower($_s['code']),
						'value'=>$product['sizes']['size_'.strtolower($_s['code'])]
					)
				);
			}
		}
		$exchange_list = $product['exchange'];
		$mator_list = array();
		if(!empty($product['mator'])){
			$fieldData = array();
			$field = FieldModel::all();
			foreach($field as $_f){
				$fieldData[$_f['id']] = $_f;
			}
			$countryData = array();
			$country = CountryModel::all();
			foreach($country as $_c){
				$countryData[$_c['id']] = $_c;
			}
			$makeData = array();
			$make = MakeModel::all();
			foreach($make as $_m){
				$makeData[$_m['id']] = $_m;
			}
			$seriesData = array();
			$series = SeriesModel::all();
			foreach($series as $_s){
				$seriesData[$_s['id']] = $_s;
			}
			$where = array();
			$mator_ids = array();
			foreach($product['mator'] as $mator){
				array_push($mator_ids,$mator['mator_id']);
			}
			$where['mator_ids'] = $mator_ids;
			$data = $this->mator_obj->getMators($where);
			if(!empty($data)){
				foreach($data as $key=>$val){
					$data[$key]['field_country_code'] = $fieldData[$val['field_id']]['field_code'].'-'.$countryData[$val['country_id']]['country_code'];
					$data[$key]['field_country_name'] = $fieldData[$val['field_id']]['field_name'].'-'.$countryData[$val['country_id']]['country_name'];
					$data[$key]['make_name'] = $makeData[$val['make_id']]['make_name'];
					$data[$key]['series_name'] = $seriesData[$val['series_id']]['series_name'];
					$data[$key]['year_name'] = '';
					if($seriesData[$val['series_id']]['from_time'] > 0){
						$data[$key]['year_name'] = date('Y/m',$seriesData[$val['series_id']]['from_time']).'~'.date('Y/m',$seriesData[$val['series_id']]['to_time']);
					}
				}
			}
			$mator_list = $data;
		}
		if(!empty($product['content']['product_params'])){
			$product['content']['product_params'] = unserialize($product['content']['product_params']);
		}
		$psale = config('product_sale_list');
		$this->assign('ptype',$ptype['list']);
		$this->assign('psale',$psale);
		$this->assign('view', $product);
		$this->assign('size_list', $size_list);
		$this->assign('exchange_list', $exchange_list);
		$this->assign('mator_list', $mator_list);
		return view('edit');
	}
	
	/**
	 * 更新产品
	 * @return mixed
	 */
	public function save()
	{
		if ($this->request->isPost()) {
			$input = input('post.');
			$supplier_id = Session::get('supplier_id');
			$input['supplier_id'] = $supplier_id;
			if(isset($input['id']) && intval($input['id']) > 0){
				$flag = $this->product_obj->insertUpdateData($input);
			}else{
				$flag = $this->product_obj->insertUpdateData($input);
			}
			if($flag){
				$result = [
					'code' => 1,
					'msg'  => '请求成功',
					'list' => $input
				];
			}else{
				$result = [
					'code' => 0,
					'msg'  => '请求失败',
					'list' => $input
				];
			}
			return json($result);
		}else{
			$this->error('更新产品数据，请求不合法！');
		}
	}	
	
	/**
	 * 删除产品
	 * @return mixed
	 */
	public function del()
	{
		if ($this->request->isPost()) {
			$input = input('post.');
			$field = $this->product_obj->delData($input);
			if($flag){
				$result = [
					'code' => 1,
					'msg'  => '请求成功',
					'list' => $input
				];
			}else{
				$result = [
					'code' => 0,
					'msg'  => '请求失败',
					'list' => $input
				];
			}
			return json($result);
		}else{
			$this->error('更新产品数据，请求不合法！');
		}
	}
	
	/**
	 * 更新产品状态
	 * @return mixed
	 */
	public function setStatus()
	{
		if ($this->request->isPost()) {
			$input = input('post.');
			$field = ProductModel::get($input['id']);
			$status = 1;
			if($field->product_status){
				$status = 0;
			}
			$field->product_status = $status;
			$flag = $field->save();
			if($flag){
				$result = [
					'code' => 1,
					'msg'  => '请求成功',
					'list' => $input
				];
			}else{
				$result = [
					'code' => 0,
					'msg'  => '请求失败',
					'list' => $input
				];
			}
			return json($result);
		}else{
			$this->error('更新产品数据，请求不合法！');
		}
	}
}
